package bbstorespringmvc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import bbstorespringmvc.model.Book;
import bbstorespringmvc.repository.BookRepository;

@Controller
public class BookCreateController {
	@Autowired BookRepository bookRepository;
	
	@RequestMapping("bookcreateauto")
	public String createFewBooks(){
		Book b1 = new Book("12345", "Springo Fantastico", "John Rizzo", 10);
		Book b2 = new Book("22345", "Javablabla", "John Rizzo", 20);
		Book b3 = new Book("33345", "The World is ...", "John Doe", 30);

		bookRepository.persist(b1);
		bookRepository.persist(b2);
		bookRepository.persist(b3);
		
		//return "redirect:main";
		return "redirect:booklist";
	}
	
    @RequestMapping("/bookcreate")
    public String bookCreate(){
        return "bookcreate";
    }


    @RequestMapping("/bookcreatesubmit")
    public ModelAndView bookCreateSubmit(@RequestParam("title") String title, @RequestParam("author") String author,
    		@RequestParam("isbn") String isbn, @RequestParam("price") int price){
    	
    	Book book = new Book();
    	
    	book.setTitle(title);
    	book.setAuthor(author);
    	book.setIsbn(isbn);
    	book.setPrice(price);
    	
    	bookRepository.persist(book);
    	
    	return new ModelAndView ("redirect:/booklist");
    	//return new ModelAndView ("redirect:/BookDisplay?id="+book.getId());  // no error => redirect to book display
    }
 }
